#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include "redispool.h"

#define IP "127.0.0.1"
#define PORT 6379
#define iWorker 2

redisContext * c;

void my_func(int sign_no)
{
	printf("Recv interrupt signal\n");
	redisFree(c);
}

int InitProcess(int iMaxNum)
{
	int num_childs = iMaxNum;
	if (num_childs > 0) {
		int child = 0;
		while (!child) {
			if (num_childs > 0) {
				switch (fork()) {
				case -1:
					exit(-1);
				case 0:
					child = 1;
					break;
				default:
					num_childs--;
					break;
				}
			} else {
				int status;
				if (-1 != wait(&status)) {
					num_childs++;
				} else {
					switch (errno) {
					case EINTR:
						kill(0, SIGHUP);
						break;
					default:
						break;
					}
				}
			}
		}

		/**
		 * for the parent this is the exit-point 
		 */
		if (!child) {
			kill(0, SIGINT);
			exit(0);
		}
	}
}

int main()
{
//	InitProcess(iWorker);

	signal(SIGINT, my_func);

	struct timeval timeout = { 1, 500000 }; // 1.5 seconds
	c = redisConnectWithTimeout(IP, PORT, timeout);
	if (c->err) {
		printf("Connection error: %s\n", c->errstr);
		exit(1);
	}else{
		printf("Connection success\n");
	}

	char buf[4096] = "";
	redisReply *reply;
	while(1)
	{
		memset(buf, 0x00, sizeof(buf));
		reply = redisCommand(c, "BLPOP wait_list 30");
		if(reply->type == REDIS_REPLY_ARRAY){
			//reply->element[0]->str: wait_list
			memcpy(buf, reply->element[1]->str, reply->element[1]->len);
			printf("pop success: %s\n", buf);
			freeReplyObject(reply);

			reply = redisCommand(c, "RPUSH already_list %s", buf);
			if(reply->type == REDIS_REPLY_INTEGER){
				printf("push success: %s\n", buf);
			}else{
				printf("push failure: %s\n", buf);
			}
			freeReplyObject(reply);
		}
	}
}

